package com.manager.common.tcp.client.handler;

import com.manager.common.tcp.client.TcpClient;
import com.manager.common.tcp.encode.impl.HeartEncode;
import com.manager.common.utils.DataTools;
import com.manager.common.utils.SocketByteConvertUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TcpClientHeartBeatHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(TcpClientHeartBeatHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            logger.info("clent: " + state.name());
            if(state == IdleState.WRITER_IDLE){

            }else if(state == IdleState.READER_IDLE){
                HeartEncode heartEncode = new HeartEncode();
                TcpClient.getInstance().send(heartEncode.encode(""));
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        DataTools.setTcpConnected(false);
    }
}
